#include "Arduino.h"
#include "protocol.h"
#include "remote.h"
#define BUFFER_MAX 512
uint8_t tcpBuffer[BUFFER_MAX];
int tcpBufferSize = 0;

const uint8_t PACKET_START[] = {'<', 'S', '>'};
const uint8_t PACKET_END[]   = {'<', 'E', '>'};
const int PKT_START_LEN = 3;
const int PKT_END_LEN   = 3;
DataItems dataItems;
void parsePacketAndUpdate(const uint8_t* packet, int packetSize) {
    int offset = PKT_START_LEN;  // 跳过 <S>
    int endOffset = packetSize - PKT_END_LEN;  // 数据区结束位置

    if (endOffset - offset < 4) return;  // 至少要有 item_count

    // 解析 item_count (little-endian uint32)
    uint32_t item_count = packet[offset + 0] |
                         (packet[offset + 1] << 8) |
                         (packet[offset + 2] << 16) |
                         (packet[offset + 3] << 24);
    offset += 4;

    for (uint32_t i = 0; i < item_count && offset < endOffset; i++) {
        if (offset >= endOffset) break;

        uint8_t name_len = packet[offset++];
        if (offset + name_len + 1 + 4 > endOffset) break;

        char name[17];
        memcpy(name, &packet[offset], name_len);
        name[name_len] = '\0';
        offset += name_len;

        char type_char = packet[offset++];

        uint32_t data_len = packet[offset + 0] |
                           (packet[offset + 1] << 8) |
                           (packet[offset + 2] << 16) |
                           (packet[offset + 3] << 24);
        offset += 4;

        if (offset + data_len > endOffset) break;

        const uint8_t* raw_data = &packet[offset];
        offset += data_len;

        if (type_char == 'f' && data_len == 4) {
            float value;
            memcpy(&value, raw_data, 4);
            if (strcmp(name, "x") == 0) dataItems.x = value;
            else if (strcmp(name, "y") == 0) dataItems.y = value;
            else if (strcmp(name, "z") == 0) dataItems.z = value;
            else if (strcmp(name, "battery") == 0) dataItems.battery = value;
            else if (strcmp(name, "yaw") == 0) dataItems.yaw = value;
        }
        else if (type_char == 'z' && data_len == 4) {
            int32_t value;
            memcpy(&value, raw_data, 4);
            if (strcmp(name, "Throttle") == 0) dataItems.Throttle = value;
        }
        // 其他类型...
    }
}


// ========================
// 配置定义
// ========================
const int MAX_PACKET_SIZE = 256;

// ========================
// 全局变量
// ========================
uint8_t packetBuffer[MAX_PACKET_SIZE];
int packetIndex = 0;                // 当前写入位置
bool packetBuilding = false;        // 是否正在构建包
bool packetReady = false;           // 包是否已完整接收

// 用于临时匹配 START/END 的滑动窗口（避免每次全匹配）
uint8_t startMatchBuffer[3] = {0};  // 滑动窗口匹配 PACKET_START
uint8_t endMatchBuffer[3] = {0};    // 滑动窗口匹配 PACKET_END

bool RemoteDataUpdated() {
    bool updated = false;

    while (client.connected() && client.available()) {
        uint8_t c = client.read();
        lastDataTime = millis();
        if (!packetBuilding) {
            // --- 状态 1：等待包头 ---
            // 使用滑动窗口维护最后 3 字节
            startMatchBuffer[0] = startMatchBuffer[1];
            startMatchBuffer[1] = startMatchBuffer[2];
            startMatchBuffer[2] = c;

            if (memcmp(startMatchBuffer, PACKET_START, PKT_START_LEN) == 0) {
                // 找到包头！开始收集
                packetIndex = 0;
                // 先写入整个 PACKET_START
                memcpy(packetBuffer + packetIndex, PACKET_START, PKT_START_LEN);
                packetIndex += PKT_START_LEN;
                packetBuilding = true;

                // 重置 endMatchBuffer
                memset(endMatchBuffer, 0, PKT_END_LEN);
            }
            // 否则：丢弃该字节（不保存）
        } else {
            // --- 状态 2：正在构建包 ---
            if (packetIndex < MAX_PACKET_SIZE) {
                packetBuffer[packetIndex++] = c;

                // 维护最后 3 字节用于匹配 PACKET_END
                endMatchBuffer[0] = endMatchBuffer[1];
                endMatchBuffer[1] = endMatchBuffer[2];
                endMatchBuffer[2] = c;

                // 检查是否收到 PACKET_END
                if (memcmp(endMatchBuffer, PACKET_END, PKT_END_LEN) == 0) {
                    // 完整包接收完成！多保存一个字节（'>』）
                    packetIndex++;  // 因为上面只写了 c，现在补上结束标志的最后一个字节
                    if (packetIndex <= MAX_PACKET_SIZE) {
                        packetReady = true;
                    } else {
                        // 包太大，丢弃
                        packetBuilding = false;
                        packetIndex = 0;
                    }
                }
            } else {
                // 缓冲区满 → 丢弃当前包
                packetBuilding = false;
                packetIndex = 0;
            }
        }
    }

    // --- 解析完整包 ---
    if (packetReady) {
        Serial.println("✅ Found complete packet!");
        parsePacketAndUpdate(packetBuffer, packetIndex);
        updated = true;

        // 重置状态
        packetBuilding = false;
        packetReady = false;
        packetIndex = 0;
        memset(packetBuffer, 0, packetIndex);
    }

    return updated;
}